﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CLUBsInterpreter.ObjectTypes;

namespace CLUBsInterpreter
{
	class Scope : Dictionary<string, CLUBsObject>
	{
		public Scope Parent;

		public void Declare(string s, CLUBsObject obj)
		{
			base[s] = obj;
		}

		new public CLUBsObject this[string s]
		{
			get
			{
				// If the key exists locally, return it
				if (base.ContainsKey(s))
				{
					return base[s];
				}
				// If not, and we have a parent, try in the parent scope
				else if (Parent != null)
				{
					return Parent[s];
				}
				// If we have no parent, return false
				else
				{
					if (StandardEnvironment.Instance.GlobalVariables.ContainsKey(s))
						return StandardEnvironment.Instance.GlobalVariables[s];
					else
						throw new KeyNotFoundException(s);
				}
			}
			set
			{
				// If the key exists locally, return it
				if (base.ContainsKey(s))
				{
					base[s] = value;
				}
				// If not, and we have a parent, try in the parent scope
				else if (Parent != null)
				{
					Parent[s] = value;
				}
				// If we have no parent, return false
				else
				{
					if (StandardEnvironment.Instance.GlobalVariables.ContainsKey(s))
						StandardEnvironment.Instance.GlobalVariables[s] = value;
					else
						throw new KeyNotFoundException(s);
				}
			}
		}
	}
}
